#include <iostream>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"
using namespace httplib;
using namespace NS_control;

static Control *ctrl_p = nullptr;

void Recovery(int signo)
{
    ctrl_p->RecoverMachine();
}

int main()
{
    signal(SIGQUIT,Recovery);
    //用户请求服务路由功能
    Server svr;
    Control ctrl;
    ctrl_p = &ctrl;

    //获取所有的题目列表
    svr.Get("/all_questions",[&ctrl](const Request &req,Response &resp){
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html;charset=utf-8");
        //返回所有的题目网页
    });
    //根据题目编号，获取题目的内容
    // /questions/100 ->正则匹配
    // R"()",保持字符串原貌，不用转义
    svr.Get(R"(/question/(\d+))",[&ctrl](const Request &req,Response &resp){
        std::string number = req.matches[1];
        std::string html;
        ctrl.question(number,&html);
        resp.set_content(html,"text/html;charset=utf-8");
    });

    //用户提交代码，使用的判题功能
    svr.Post(R"(/judge/(\d+))",[&ctrl](const Request &req,Response &resp){
        std::string number = req.matches[1];
        //resp.set_content("这是判题功能："+number,"text/plain;charset=utf-8");
        std::string result_json;
        ctrl.Judge(number,req.body,&result_json);
        resp.set_content(result_json,"application/json;charset=utf-8");
    });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0",8080);
    return 0;
}